<template>
  <div class="user-login-layout  home-main-box">

    <div class="user-login-form form">
      <el-form ref="bindForm" key="bindForm" :model="form" :rules="rules">

        <el-form-item prop="user" style="width: 100%;">
          <el-input key="bind-user-input" v-model.trim="form.user" type="text" placeholder="请绑定您的电话/邮箱" class="user-pwd-input">
            <svg-icon slot="prefix" icon-class="user" />
          </el-input>
        </el-form-item>

        <el-form-item prop="pwd">
          <pwdInput key="bind-pwd-input" v-model.trim="form.pwd" show-password placeholder="请输入您的密码" class="user-pwd-input">
            <svg-icon icon-class="pwd" />
          </pwdInput>
        </el-form-item>

        <div class="code-box">
          <el-form-item prop="code">
            <el-input key="bind-code-input" v-model.trim="form.code" type="text" placeholder="短信/邮箱验证码" maxlength="6" />
          </el-form-item>
          <el-button class="msg-btn" size="small" type="primary" @click="sendCode">{{ codeText }}</el-button>
        </div>

        <div class="pwd-box flex">
          <span class="find-pwd pointer" style="margin-right: 24px;font-size: 14px;" @click="handleChangeType('findPwd')">忘记密码</span>
          <span class="find-pwd pointer" style="font-size: 14px;" @click="handleChangeType('login')">已有账号,去登录</span>
        </div>

        <div class="btn-list bind-btn">
          <el-button
            v-loading="bindLoading"
            type="success"
            style="width: 100%;height: 48px;"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            @click="submitBinding"
          >立即绑定</el-button>
        </div>

      </el-form>

    </div>
  </div>
</template>
<script>
import {
  userIsRes,
  upWeixinUser,
  findCampaignCount,
  emailRegister, // 邮箱验证码获取
  smsRegister // 手机验证码获取

} from '@/api/user.js'
import {
  mapMutations
} from 'vuex'
import {
  getDefultPath
} from '@/utils/index.js'

export default {
  props: {
    wxInfo: {
      type: Object,
      required: true,
      default: function() {
        return {}
      }
    }
  },
  data() {
    const isValidCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.length < 4) {
        callback(new Error('验证码格式错误'))
      } else {
        callback()
      }
    }

    const isValidUsername = async(rule, value, callback) => {
      var MobileRegex = /^1[0-9]{10}$/
      var mailRegex = /^\w*@[-a-zA-Z0-9]{1,20}\.[0-9a-z]{2,3}$/
      if (!MobileRegex.test(value) && !mailRegex.test(value)) {
        return callback(new Error('请输入正确的手机或者邮箱!'))
      } else {
        try {
          const res = await userIsRes({
            info: value
          })
          // console.log(res)
          if (res.data.code * 1 === 20000 && res.data.flag) {
            return callback()
          } else {
            return callback(res.data.message || new Error('该手机或邮箱已被注册,请登录后绑定'))
          }
        } catch (err) {
          return callback(err.data.message || new Error('该手机或邮箱已被注册,请登录后绑定'))
        }

        // console.log(res, '你好')
      }
      // if (!MobileRegex.test(value)) {
      //   if (!mailRegex.test(value)) {

      //   } else {
      //     return callback()
      //   }
      // } else {
      //   return callback()
      // }
    }

    return {
      bindLoading: false,
      code: undefined, // 验证码图片路径
      codeTimer: undefined, // 验证码定时器
      codeDownSec: undefined, // 验证码定时器
      codeText: '获取验证码',
      form: {
        user: '',

        // user: '15360089159',
        pwd: '',
        // pwd: '12345678a',
        code: ''
      },
      rules: {
        user: [{
          required: true,
          message: '请输入电话/邮箱',
          trigger: 'blur'
        },
        {
          validator: isValidUsername,
          trigger: 'blur'
        }
        ],
        pwd: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        code: [{
          validator: isValidCode,
          trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
  },
  methods: {
    ...mapMutations({
      setToken: 'user/SET_TOKEN'

    }),
    // 清除表单数据
    resetForm() {
      this.$refs['bindForm'].resetFields()
    },
    // 切换显示类型,去忘记密码页面
    handleChangeType(type) {
      this.resetForm()
      this.$emit('changeType', type)
    },
    // 发送手机/邮箱验证码
    sendCode() {
      if (this.codeTimer) return false
      this.$refs['bindForm'].validateField('user', (errMsg) => {
        if (errMsg) {} else {
          if (this.form.user.indexOf('@') === -1) {
            this.sendPhoneCode()
          } else {
            this.sendEmailCode()
          }
        }
      })
    },
    // 开启倒计时
    runTime() {
      this.codeDownSec = 60
      this.codeTimer = setInterval(() => {
        if (this.codeDownSec > 1) {
          this.codeDownSec -= 1
          this.codeText = this.codeDownSec + 's'
        } else {
          this.codeText = '获取验证码'
          clearInterval(this.codeTimer)
          this.codeTimer = undefined
        }
      }, 1000)
    },

    // 发送手机验证码
    async sendPhoneCode() {
      const obj = {
        account: this.form.user,
        type: 'wechat' // 绑定微信字段
      }

      const {
        data
      } = await smsRegister(obj)
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },

    // 发送邮箱验证码

    async sendEmailCode() {
      const obj = {
        account: this.form.user,
        type: 'wechat' // 绑定微信字段
      }
      const {
        data
      } = await emailRegister(obj)
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },

    // 提交绑定
    submitBinding() {
      this.bindLoading = true
      this.$refs['bindForm'].validate(async(valid) => {
        if (valid) {
          this.wxBindUser()
        } else {
          this.bindLoading = false
          return false
        }
      })
    },

    // 微信账号绑定用户名账号
    async wxBindUser() {
      let formlist = {}
      // 判断是邮箱登录还是手机号码登录
      if (this.form.user.indexOf('@') !== -1) {
        formlist = {
          info: this.form.user,
          pwd: this.form.pwd,
          code: this.form.code
        }
      } else {
        formlist = {
          info: this.form.user,
          pwd: this.form.pwd,
          code: this.form.code
        }
      }
      const obj = this.wxInfo
      formlist = { ...formlist,
        headimgurl: obj.headimgurl,
        unionid: obj.unionid,
        nickname: obj.nickname
      }

      try {
        const res = await upWeixinUser(formlist)

        const {
          data
        } = res

        if (data.code === 20000) {
          this.$message.closeAll()
          this.$message({
            message: '登录成功，即将跳转页面',
            type: 'success'
          })
          this.setToken(res.data.data.token)

          const userInfo = await this.$store.dispatch('user/getInfo')
          const path = getDefultPath(userInfo.roleName)
          this.$router.replace({
            path
          })

          // this.isFirstLogin()
          //
        } else {
          this.bindLoading = false
          this.$message.closeAll()
          this.$message.error(data.message || '绑定失败，请稍后重试')
        }
      } catch (err) {
        this.bindLoading = false
        this.$message.closeAll()
        this.$message.error(err.data.message || '绑定失败，请稍后重试')
      }
    },
    // 验证是否是首次登录
    async isFirstLogin() {
      const res = await findCampaignCount(this.$store.state.user.unit)
      this.$message.closeAll()
      this.$message({
        message: '登录成功，即将跳转页面',
        type: 'success'
      })

      if (res.data.data.length > 0) {
        this.$router.replace({
          path: '/'
        })
      } else {
        this.$router.replace({
          path: '/'
        })
      }
      // showWindowMessage(4, res.data.message)
      // this.setCookie(this.form.user, this.form.pwd, 7)
    }

  }
}
</script>

<style lang="scss" scoped>
  @import './style/form.scss'
</style>
